package com.wushi.lenovo.asia5b.app_ui.credit.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.mvp.base.BaseMvpActivity;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.credit.mvpview.CreditTransferActivityView;
import com.wushi.lenovo.asia5b.app_di.credit.presenter.CreditTransferActivityPresenter;
import com.wushi.lenovo.asia5b.app_model.other.ShareBean;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.ShareDialog;
import com.wushi.lenovo.asia5b.app_utils.WFileUtil;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;
import com.wushi.lenovo.asia5b.app_utils.helper.CrashHelper;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.BarcodeType;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/1/16.
 * 转账界面
 */
public class CreditTransferActivity extends BaseMvpActivity<CreditTransferActivityView, CreditTransferActivityPresenter> implements CreditTransferActivityView, QRCodeView.Delegate {
    @BindView(R.id.rb_credit_scan)
    RadioButton rb_credit_scan;
    @BindView(R.id.rb_credit_mycode)
    RadioButton rb_credit_mycode;
    @BindView(R.id.rg_credit)
    RadioGroup rg_credit;
    @BindView(R.id.ll_credit_scan)
    FrameLayout ll_credit_scan;
    @BindView(R.id.ll_credit_mycode)
    ScrollView ll_credit_mycode;
    @BindView(R.id.zbarview)
    ZXingView mZBarView;
    @BindView(R.id.iv_mycode_img)
    ImageView iv_mycode_img;//二维码
    @BindView(R.id.tv_mycode_name)
    TextView tv_mycode_name;//姓名
    @BindView(R.id.tv_mycode_email)
    TextView tv_mycode_email;//邮箱
    @BindView(R.id.pb_mycode)
    ProgressBar progressBar;
    String email = null;
    private Bitmap mBitmap;
    private File file;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_credittransfer;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        email = UserInfo.getUserInfo().getEmail();
        if (TextUtils.isEmpty(email)) {
            email = "";
        }
        getFile();
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        tv_mycode_name.setText(UserInfo.getUserInfo().getName());
        tv_mycode_email.setText(email);
        mZBarView.setDelegate(this);
        rb_credit_scan.setChecked(true);
        setImageByFile();

    }


    private void setImageByFile() {
        boolean granted = new RxPermissions(mActivity).isGranted(Manifest.permission.READ_EXTERNAL_STORAGE);
        EyeUtils.tagPermission();
        if (granted) {
            if (getFile().exists()) {
                Glide.with(mActivity)
                        .load(getFile())
                        .into(iv_mycode_img);
                d("--->>>>>>>>---setImageByFile");
            } else {
                getPresenter().getImageByBitmap(this, email);
            }
        } else {
            getPresenter().getImageByBitmap(this, email);
        }


    }

    @Override
    protected void initData() {

    }

    private File getFile() {
        if (file == null || !file.exists()) {
            String imagePath = WFileUtil.createImagePath(mActivity, email);
            file = new File(imagePath);
        }
        return file;
    }

    @Override
    protected void initEvent() {
        rg_credit.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rb_credit_mycode.getId()) {
                    ll_credit_mycode.setVisibility(View.VISIBLE);
                } else {
                    ll_credit_mycode.setVisibility(View.GONE);
                }
            }
        });
    }

    //保存二维码
    private void saveCode(boolean isShare) {

        new RxPermissions(this)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        if (getFile().exists()) {//文件已经存在
                            toastFilePath(getFile().getAbsolutePath(), isShare);
                        } else {
                            getPresenter().getImagePathByCode(mBitmap, getFile(), isShare);
                        }

                    } else {
                        ToastUtil.showToast(getString(R.string.permission_error1));
                    }
                });
        EyeUtils.tagPermission();
    }

    private void toastFilePath(String imgPath, boolean isShare) {
        if (isShare) {
            ShareBean shareBean = new ShareBean();
            shareBean.shareType = ShareBean.IMG;
            shareBean.setBitmap(mBitmap);
            shareBean.setImgFilePath(imgPath);
            new ShareDialog(this, shareBean).show();
        } else {
            if (!TextUtils.isEmpty(imgPath)) {
                String s=getString(R.string.save_success)+":"+imgPath;
                ToastUtil.showToast(s);
            } else {
                ToastUtil.showToast(getString(R.string.save_fail));
            }
        }
    }

    @Override
    public void getImageByBitmapResult(Bitmap bitmap) {
        iv_mycode_img.setImageBitmap(bitmap);
        mBitmap = bitmap;
    }

    @Override
    public void getImagePathByCodeResult(String imgPath, boolean isShare) {
        toastFilePath(imgPath, isShare);
    }

    @OnClick({
            R.id.ll_scan_addphoto,
            R.id.tv_ctransfer_emial,
            R.id.tv_ctransfer_share,
            R.id.tv_ctransfer_save
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_scan_addphoto: {
                new RxPermissions(this)
                        .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                PictureSelector.create(CreditTransferActivity.this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles
                                        .previewImage(true)// 是否可预览图片
                                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                        .compress(false)// 是否压缩
                                        .openClickSound(false)// 是否开启点击声音
                                        .maxSelectNum(1)
                                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                            } else {
                                ToastUtil.showToast(getString(R.string.permission_error1));
                            }
                        });
                EyeUtils.tagPermission();
            }
            break;
            case R.id.tv_ctransfer_emial://通过邮箱转账
                startActivity(new Intent(this, TransferEmailActivity.class));
                break;
            case R.id.tv_ctransfer_share:
                saveCode(true);
                break;
            case R.id.tv_ctransfer_save:
                saveCode(false);

                break;
            default:
                break;
        }
    }

    private void vibrate() {
//        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//        vibrator.vibrate(200);
    }

    boolean isStartScanDetailActivity = false;

    @Override
    public void onScanQRCodeSuccess(String result) {
        d("--->>>>>>>>---" + "result:" + result);
//        ToastUtil.showToast(result);
        vibrate();
        if (mZBarView != null) {
            mZBarView.startSpot(); // 开始识别
        }
        if (!TextUtils.isEmpty(result) && !isStartScanDetailActivity) {
            isStartScanDetailActivity = true;
            Intent intent = new Intent(this, TransferEmailActivity.class);
            intent.putExtra(CommonConstant.EMAIL, result);
            startActivity(intent);
        }

    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
//        String tipText = mZBarView.getScanBoxView().getTipText();
//        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
//        if (isDark) {
//            if (!tipText.contains(ambientBrightnessTip)) {
//                mZBarView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
//            }
//        } else {
//            if (tipText.contains(ambientBrightnessTip)) {
//                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
//                mZBarView.getScanBoxView().setTipText(tipText);
//            }
//        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        CrashHelper.postCatchedException(new Throwable("扫描失败"));
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (mZBarView != null) {
            mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
            mZBarView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式
            mZBarView.setType(BarcodeType.TWO_DIMENSION, null); // 只识别二维条码
            mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isStartScanDetailActivity = false;
    }

    @Override
    protected void onStop() {
        if (mZBarView != null) {
            mZBarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (mZBarView != null) {
            mZBarView.onDestroy(); // 销毁二维码扫描控件
        }
        super.onDestroy();
    }

    @Override
    public void showLoadingBar(Object dississTag) {
        if (TextUtils.equals(dississTag+"", "progress")) {
            progressBar.setVisibility(View.VISIBLE);
        } else {
            super.showLoadingBar(dississTag);
        }

    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        super.dismissLoadingBar(dississTag);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK)
            return;

        switch (requestCode) {

            case PictureConfig.CHOOSE_REQUEST: {
                mZBarView.showScanRect();
                // 图片选择
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList != null && selectList.size() > 0) {
                    LocalMedia localMedia = selectList.get(0);
                    String path = localMedia.getPath();
                    d("--->>>>>>>>---path:" + path);
                    mZBarView.decodeQRCode(path);
                }
                break;
            }
        }
    }

}
